import * as THREE from 'three'
import createApp from '../../core'

function createQuadraticBezierCurve (dom: HTMLElement) {
  const { camera, scene, gui } = createApp(dom)
  camera.position.set(0, 0, 100)
  camera.lookAt(scene.position)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  const { color } = data
  const { startPoint, controlPoint, endPoint } = getPoints()
  const curve = new THREE.QuadraticBezierCurve(startPoint, controlPoint, endPoint)
  const points = curve.getPoints(50)
  const geometry = new THREE.BufferGeometry().setFromPoints(points)
  const material = new THREE.LineBasicMaterial({ color })
  const QuadraticBezier = new THREE.Line(geometry, material)

  scene.add(QuadraticBezier)

  function changeMesh () {
    const { startPoint, controlPoint, endPoint } = getPoints()
    curve.v0.copy(startPoint)
    curve.v1.copy(controlPoint)
    curve.v2.copy(endPoint)
    const points = curve.getPoints(50)
    geometry.setFromPoints(points)
  }

  const folder0 = gui.addFolder('起点')
  folder0.add(data.v0, 'x', -200, 200).onChange(changeMesh)
  folder0.add(data.v0, 'y', -200, 200).onChange(changeMesh)

  const folder1 = gui.addFolder('中间控制点')
  folder1.add(data.v1, 'x', -200, 200).onChange(changeMesh)
  folder1.add(data.v1, 'y', -200, 200).onChange(changeMesh)

  const folder2 = gui.addFolder('终点')
  folder2.add(data.v2, 'x', -200, 200).onChange(changeMesh)
  folder2.add(data.v2, 'y', -200, 200).onChange(changeMesh)

  gui.addColor(data, 'color').onChange(() => {
    material.color = new THREE.Color(data.color)
  })
}

const data = {
  v0: { x: -10, y: 0 },
  v1: { x: -5, y: 15 },
  v2: { x: 20, y: 15 },
  color: 0xff0000
}
const startPoint = new THREE.Vector2()
const controlPoint = new THREE.Vector2()
const endPoint = new THREE.Vector2()

function getPoints () {
  const { v0, v1, v2 } = data
  startPoint.set(v0.x, v0.y)
  controlPoint.set(v1.x, v1.y)
  endPoint.set(v2.x, v2.y)
  return { startPoint, controlPoint, endPoint }
}

export {
  createQuadraticBezierCurve
}
